<template>
  <div class="h-full flex flex-col">
    <ds-title v-if="title" :title="title" :alias="alias"/>
    <div class="h-full flex flex-wrap">
      <div class="flex ds-counts w-1/2 justify-center items-center" v-for="n of Object.keys(name)">
        <div class="rounded-full flex justify-center items-center w-14 h-14 bg-indigo-600 bg-opacity-10 text-white mr-5">
          <ds-icon :name="icon[n]" class="text-4xl"/>
        </div>
        <div class="flex flex-col">
          <div :id="n" class="text-white text-2xl"></div>
          <span class="text-primary text-sm">{{name[n]}}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import HTTP from '../apis'
import {CountUp} from 'countup.js'
import {defineComponent, onMounted, ref, inject} from 'vue';
import DsTitle from "./DsTitle.vue";
import DsIcon from "./DsIcon.vue";
import {AxiosResponse} from "axios";
import {Emitter} from 'mitt';

export default defineComponent({
  name: 'DsCount',
  components: {DsIcon, DsTitle},
  props: {
    name: {
      type: Object,
      default() {
        return {}
      }
    },
    title: {
      type: String,
      default: ''
    },
    alias: {
      type: String,
      default: ''
    },
    icon: {
      type: Object,
      default() {
        return {}
      }
    },
    unit: {
      type: String,
      default: ''
    },
    endpoint: {
      type: String,
      default: '',
      required: true
    },
    query: {
      type: Object,
      default() {
        return {}
      }
    },
    keymap: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  setup(props) {
    let r: AxiosResponse, init: boolean = true;
    const {to, name, query, keymap} = props
    const {endpoint} = inject<any>('Config')
    const emitter = inject<Emitter>('Emitter');
    const url = props.endpoint || endpoint

    const countUp = {}
    const getCountData = async () => {
      if (url) {
        r = await HTTP.get(url, {
          params: query
        })
      }
      Object.keys(name).forEach((value: string) => {
        const element = document.getElementById(value)
        const toValue = url ? (r && r.data.data) : (Math.ceil(Math.random() * 100 + 10))
        if (element) {
          if (!countUp[value]) {
            countUp[value] = new CountUp(element, !url ? toValue : (keymap[value] ? toValue[keymap[value]] : 0));
          }
          if (!countUp[value].error) {
            init ? countUp[value].start() : countUp[value].update(toValue[keymap[value]] + 1000);
          } else {
            console.error(countUp[value].error);
          }
        }
      })
    }

    onMounted(async () => {
      await getCountData()
      init = true
      emitter?.on('update', getCountData)
    })
    return {
    }
  }
})
</script>
